package cn.fcq.user.service.impl;

import cn.fcq.basic.constants.BaseConstant;
import cn.fcq.basic.dto.RegisterDto;
import cn.fcq.basic.exception.BusinessException;
import cn.fcq.basic.util.MD5Utils;
import cn.fcq.basic.util.StrUtils;
import cn.fcq.user.domain.Logininfo;
import cn.fcq.user.domain.User;
import cn.fcq.user.mapper.LogininfoMapper;
import cn.fcq.user.mapper.UserMapper;
import cn.fcq.user.service.IUserService;
import cn.fcq.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuchao
 * @since 2022-06-16
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public void phoneRegister(RegisterDto dto) {
        //1.校验
        String phone = dto.getPhone();
        String smsCode = dto.getSmsCode();
        String password = dto.getPassword();
        String passwordRepeat = dto.getPasswordRepeat();
        //空校验
        if(StringUtils.isEmpty(phone)||
                StringUtils.isEmpty(smsCode)||
                StringUtils.isEmpty(password)||
                StringUtils.isEmpty(passwordRepeat)
        ){
            throw new BusinessException("参数不能为空哦");
        }
        //密码和确认密码是否一致
        if (!password.equals(passwordRepeat)){
            throw new BusinessException("密码不一致！");
        }
        //2.验证码判断
        String key = BaseConstant.RegisterConstants.REGISTER_SMS_PREFIX + phone;
        Object smsCodeTmp = redisTemplate.opsForValue().get(key);
        //2.1 没有，验证码过期，请重新获取
        if(smsCodeTmp == null){
            throw new BusinessException("验证码已失效，请重新获取！");
        }
        //2.2 拿到了，判断是否一致
        if(!smsCode.equalsIgnoreCase(smsCodeTmp.toString().split(":")[0])){
            // 不一致 验证码错误，请核对
            throw new BusinessException("请输入正确的短信验证码！");
        }
        // 一致，往下走
        //3.保存数据 t_user + t_logininfo
        User user = dto2User(dto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

    }
    //根据user对象获取logininfo
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }
    //初始化user对象
    private User dto2User(RegisterDto dto) {
        User user = new User();
        user.setUsername(dto.getPhone());
        user.setPhone(dto.getPhone());
        //获取盐值
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(dto.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    @Override
    public void save(User user) {
        //初始化username
        if(user.getUsername() == null || "".equals(user.getUsername())){
            user.setUsername(user.getPhone());
        }
        //设置用户的盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //设置用户的加密密码
        user.setPassword(MD5Utils.encrypByMd5(user.getPassword() + salt));
        //根据user对象获取logininfo对象
        Logininfo logininfo = user2Logininfo(user);
        //新增日志对象
        logininfoMapper.save(logininfo);
        //设置user对象的loginid
        user.setLogininfoId(logininfo.getId());
        //保存user对象
        userMapper.save(user);
    }

    /**
     * 修改用户需要修改的对应的logininifo
     * @param user
     */
    @Override
    public void update(User user) {
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        BeanUtils.copyProperties(user,logininfo);
        logininfoMapper.update(logininfo);
        userMapper.update(user);
    }

    /**
     * 删除用户需要删除的对应的logininifo
     * @param id
     */
    @Override
    public void removeById(Long id) {
        logininfoMapper.deleteById(userMapper.loadById(id).getLogininfoId());
        userMapper.deleteById(id);
    }

}
